package com.audition.thread.day01;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author xukang
 * @date 2021-03-09 10:09
 */
public class FibonacciDemo extends RecursiveTask<Integer> {
    //RecursiveTask 类是对ForkJoinTask 的一个简单的包装
    int anInt;

    public FibonacciDemo(int anInt) {
        this.anInt = anInt;
    }
    @Override
    protected Integer compute() {
        if (anInt <= 1) {
            return anInt;
        }
            FibonacciDemo f1 = new FibonacciDemo(anInt-1);
            f1.fork();
            FibonacciDemo f2 = new FibonacciDemo(anInt-2);
            f2.fork();
            return f1.join() + f2.join();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        for (int i = 0; i < 10; i++) {

            ForkJoinTask<Integer> task = forkJoinPool.submit(new FibonacciDemo(i));
            System.out.println(task.get());

        }
    }
}
